package com.home.qh.webapp.controller;

import java.beans.PropertyEditorSupport;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.City;
import com.home.qh.model.Port;
import com.home.qh.service.CityManager;
import com.home.qh.service.PortManager;

@Controller
@RequestMapping("/admin/portForm.*")
public class PortFormController extends BaseFormController {
	private transient final Log log = LogFactory.getLog(PortFormController.class);
	private PortManager mgr;
	private CityManager cityManager;
    
    @Autowired
    private ApplicationContext context;

    @Autowired
    public void setPortManager(PortManager portManager) {
        this.mgr = portManager;
    }
    
    @Autowired
    public void setCityManager(CityManager cityManager) {
        this.cityManager = cityManager;
    }	
        
    public PortFormController() {
        setCancelView("redirect:mainMenu.html");
        setSuccessView("redirect:/admin/portList.html");
    }
    
    @Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) {
		super.initBinder(request, binder);
        binder.registerCustomEditor(City.class, "city", 
                new PropertyEditorSupport() {
        	public void setAsText(String id)
        	{
        		long longId = Long.parseLong(id);
        		if (longId > 0)
        		{
        			City city = cityManager.get(longId);
        			setValue(city);
        		}
        	}
        });
		
	}
    
    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	 ModelAndView view = new ModelAndView("admin/portForm");
         view.addObject("cityList", cityManager.getAll());
    	
    	log.debug("entering 'showForm' method...");
        if (!isFormSubmission(request)) {
            String portId = request.getParameter("id"); 
            Port port = null;
	        if (portId == null || isAdd(request)) {
	        	port = new Port();
	        } else if (!StringUtils.isBlank(portId)) {
	        	port = mgr.get(Long.parseLong(portId));
	        }
	        view.addObject("port", port);
        }
    	return view;
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Port port, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            if (!StringUtils.equals(request.getParameter("from"), "list")) {
                return getCancelView();
            } else {
                return getSuccessView();
            }
        }


        log.debug("entering 'onSubmit' method...");

        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
        	mgr.remove(port.getId());
            return getSuccessView();
        } else {
        	if (port == null)
        		port = new Port();   
        	log.debug("Save port");
        	
        	mgr.save(port);
            return getSuccessView();        	
        }
    }

    private boolean isFormSubmission(HttpServletRequest request) {
        return request.getMethod().equalsIgnoreCase("post");
    }

    protected boolean isAdd(HttpServletRequest request) {
        String method = request.getParameter("method");
        return (method != null && method.equalsIgnoreCase("add"));
    }  

}
